package com.wan37.gate;

import com.wan37.common.xml.XMLUtils;
import com.wan37.gate.global.reference.SpringContextHolder;
import com.wan37.gate.server.GateServer;
import com.wan37.gate.server.GateToAuthConnection;
import com.wan37.gate.server.GateToLogicConnection;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.concurrent.*;


/**
 * Gate网关服务器启动
 *
 * @author : luoyong
 * @date : 2020-05-26 16:35
 **/
public class GateStarter {

    private static final Logger logger = LoggerFactory.getLogger(GateStarter.class);

    private static int gateId;
    /**
     * 从gate-config.xml配置文件中获取到数据。
     */
    private static String gateServerIp;
    private static int gateServerPort;
    private static String authServerIp;
    private static int authServerPort;
    private static String logicServerIp;
    private static int logicServerPort;

    public static void main(String[] args) {
        GateStarter.configAndStart();
    }

    private static void configAndStart() {

        Element gate = XMLUtils.parseXmlFile("gate/gate-config.xml");

        assert gate != null;
        gateId = Integer.parseInt(gate.attributeValue("id").trim());
        logger.info("gateId= " + gateId);

        Element gateServerElement = gate.element("gateServer");
        gateServerIp = gateServerElement.attributeValue("ip").trim();
        gateServerPort = Integer.parseInt(gateServerElement.attributeValue("port".trim()));
        logger.info("gateserverIp: {},  gateserverPort: {}", gateServerIp, gateServerPort);

        Element authServerElement = gate.element("authServer");
        authServerIp = authServerElement.attributeValue("ip").trim();
        authServerPort = Integer.parseInt(authServerElement.attributeValue("port").trim());
        logger.info("GateAuthConnection authServerIp: {},  authServerPort: {}", authServerIp, authServerPort);

        Element logicServerElement = gate.element("logicServer");
        logicServerIp = logicServerElement.attributeValue("ip").trim();
        logicServerPort = Integer.parseInt(logicServerElement.attributeValue("port").trim());
        logger.info("GateLogicConnection logicServerIp: {},  logicServerPort: {}", logicServerIp, logicServerPort);

        new ClassPathXmlApplicationContext("spring/gate-spring-config.xml");

        GateServer gateServer = (GateServer) SpringContextHolder.getApplicationContext().getBean("gateServer");
        gateServer.setPort(gateServerPort);


        new Thread(gateServer).start();
        new Thread(new GateToAuthConnection(authServerIp, authServerPort)).start();
        new Thread(new GateToLogicConnection(logicServerIp, logicServerPort)).start();
    }


}

